<?php
/**
 * 购物车
 * Created by PhpStorm.
 * User: liyy
 * Date: 2017/7/27 0027
 * Time: 下午 3:39
 */

namespace app\api\model;

use think\Db;
use think\Model;
class Cart extends Model{

    /**
     * 购物车新增
     */
    public function cartAdd($data){
        if (empty($data['user_id']) || empty($data['session_id']) || empty($data['goods_sn']) || empty($data['goods_name']) || empty($data['goods_price']) || empty($data['goods_num']) || empty($data['item_id'])){
            return false;
        }
        if ($data['market_price'] <= 0){
            $map['market_price'] = 0;
        }
        if (empty($data['member_goods_price'])){
            $map['member_goods_price'] = 0;
        }
        if (!empty($data['spec_key'])){
            $map['spec_key'] = $data['spec_key'];
        }
        if (!empty($data['spec_key_name'])){
            $map['spec_key_name'] = $data['spec_key_name'];
        }
        if (!empty($data['bar_code'])){
            $map['bar_code'] = $data['bar_code'];
        }
        $map['user_id'] = $data['user_id'];
        $map['session_id'] = $data['session_id'];
        $map['goods_id'] = $data['goods_id'];
        $map['goods_sn'] = $data['goods_sn'];
        $map['goods_name'] = $data['goods_name'];
        $map['goods_price'] = $data['goods_price'];
        $map['goods_num'] = $data['goods_num'];
        $map['item_id'] = $data['item_id'];
        $map['add_time'] = time();
        $return = Db::name('cart')->insert($map);
        if ($return){
            return $return;
        }else{
            return false;
        }
    }

    /**
     * 查找该条记录是否存在
     */
    public function cartFind($data){
        $where['goods_id'] =  $data['goods_id'];
        $where['item_id'] = $data['item_id'];
        $where['user_id'] = $data['user_id'];
        $data = Db::name('cart')->where($where)->find();
        if ($data){
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 编辑购物车
     */
    public function cartEdit($data){
        if ($data['cart_id'] <= 0 || empty($data['cart_id'])){
            return false;
        }
        if ($data['num'] > 0 || !empty($data['num'])){
            $map['goods_num'] = $data['num'];
        }
        if ($data['selected'] == 1 || $data['selected'] == 1){
            $map['selected'] = $data['selected'];
        }
        $where['id'] = $data['cart_id'];
        $return = Db::name('cart')->where($where)->update($map);
        if ($return){
            return $return;
        }else{
            return false;
        }
    }

    /**
     * 删除购物车
     */
    public function cartDel($data){
        if ($data['cartid'] <=0 ){
            return false;
        }
        $where['id'] = $data['cartid'];
        $return = Db::name('cart')->where($where)->delete();
        if ($return){
            return $return;
        }else{
            return false;
        }
    }
}